<template>
  <div id="app" style="overflow: hidden;width:100%;height:100%;">
    <vxe-grid ref="xGrid" v-bind="grid_options" :row-config="{height:36}" @form-reset="formResetEvent">
      <template #toolbar_tools>
        <vxe-button @click="exportModal" icon="fa fa-arrow-down" class="export"></vxe-button>
      </template>
    </vxe-grid>
    <equipmentDdetail ref="equipmentDdetail"></equipmentDdetail>
    <equipmentMaintenanceForm ref="equipmentMaintenanceForm"></equipmentMaintenanceForm>
  </div>


</template>

<script>
import {godownEntryApi} from "@/api/equip/godownEntryApi";
import {accountQueryApi} from '@/api/equip/accountQueryApi.js'
import equipmentDdetail from './components/equipmentDdetail.vue'
import equipmentMaintenanceForm from './components/equipmentMaintenanceForm.vue'
import {warehouseManagement} from '@/api/equip/warehouseManagement.js'
import util from '@/utils/util'
import VXETable from "vxe-table";
import {getInfo} from "@/api/login";
import {listDept} from "@/api/system/dept";
import moment from "moment";

export default {
  name: 'equipmentDdetailIndex',
  components: {equipmentDdetail, equipmentMaintenanceForm},
  props: {
    row: {
      type: Object,
    },
    formData: {
      type: Object,
    },
  },
  data() {
    return {
      grid_options: {
        border: true,
        stripe: true,
        showHeaderOverflow: false,
        showOverflow: true,
        keepSource: true,
        id: 'full_edit_1',
        height: 700,
        rowId: 'id',  //指定记录主键
        rowConfig: {
          isHover: true
        },
        columnConfig: {
          resizable: true
        },
        customConfig: {
          storage: true,
          // checkMethod: this.checkColumnMethod
        },
        sortConfig: {
          trigger: 'cell',
          remote: true
        },
        filterConfig: {
          remote: true
        },
        formConfig: {
          form: true, // 启用表单代理
          size: "medium",        //尺寸
          titleAlign: "right",  //所有项的标题对齐方式
          titleWidth: "120", //标题宽度
          titleColon: true,     //是否显示标题冒号
          items: [
            {
              field: 'gldwbm',
              title: '单位:',
              span: 6,
              itemRender: {
                name: '$select',
                options: [],
                props: {placeholder: '---请选择单位---'},
                events: {change: this.gldwbmChangeEvent}
              },
            },
            {
              field: 'djbm',
              title: '入库单号:',
              span: 6,
              itemRender: {name: '$input', props: {placeholder: '请输入入库单号'}},
            },
            {
              field: 'ccbm',
              title: '出厂编码:',
              span: 6,
              itemRender: {name: '$input', props: {placeholder: '请输入出厂编码'}},
            },
            {
              field: 'sbmc',
              title: '设备名称:',
              span: 6,
              itemRender: {name: '$input', props: {placeholder: '请输入出厂编码'}},
              folding: true,
            },
            {
              field: 'djrq',
              title: '入库日期',
              span: 6,
              itemRender: {name: '$input', props: {type: 'date', placeholder: '请输入日期'}},
              folding: true,
            },
            {
              field: 'djrq_to',
              title: '至',
              span: 6,
              itemRender: {name: '$input', props: {type: 'date', placeholder: '请输入日期'}},
              folding: true,
            },
            {
              field: 'sblxbm',
              title: '设备类型:',
              span: 6,
              itemRender: {name: '$select', options: [], props: {placeholder: '---请选择设备类型---'}},
              folding: true,
            },
            {
              field: 'sskfbm',
              title: '库房名称:',
              span: 6,
              itemRender: {name: '$select', options: [], props: {placeholder: '---请选择仓库名称---'}},
              folding: true,
            },
            {
              span: 6, collapseNode: true, align: 'right', itemRender: {
                name: '$buttons', children: [
                  {props: {type: 'submit', content: '查询', status: 'primary', icon: 'fa fa-search'}},
                  {props: {type: 'reset', content: '重置', icon: 'fa fa-reply'}},
                ]
              }
            }
          ]
        },
        toolbarConfig: {
          buttons: [
            // { buttonRender: { name: 'add', events: { click: this.addRowModal } } }, // 新增

          ],
          refresh: true,
          custom: true,
          slots: {
            buttons: 'toolbar_tools'    //按钮列表//
          }
        },
        pagerConfig: {
          pageSize: 10,
          pageSizes: [5, 10, 15, 20, 50, 100],
          layouts: ['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total'],
          background: true,
          fixed: true,
        },
        proxyConfig: {
          seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
          sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
          filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
          form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
          // 对应响应结果 { result: [], page: { total: 100 } }
          props: {
            result: 'data.records', // 配置响应结果列表字段
            total: 'data.total' // 配置响应结果总页数字段
          },
          // 只接收Promise，具体实现自由发挥
          ajax: {
            // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
            query: async ({page, sorts, filters, form}) => {
              // =====给表单项赋初始值======
              await this.initFormData(form);
              //    this.enableDefault = false;
              const queryParams = Object.assign({}, form)
              // const queryParams = this.initFormData(form)
              // 处理排序条件
              const firstSort = sorts[0]
              if (firstSort) {
                queryParams.sort = firstSort.property
                queryParams.order = firstSort.order
              }
              // 处理筛选条件

              filters.forEach(({property, values}) => {
                queryParams[property] = values.join(',')
              })
              return this.queryData(page, queryParams)
            },
          }
        },
        columns: [
          {type: 'seq', title: '序号', width: "60px", align: 'center', headerAlign: 'center'},
          {field: 'gldwmc', title: '单位', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {
            field: 'djbm',
            title: '入库单号',
            minWidth: "160px",
            align: 'center',
            headerAlign: 'center',
            cellRender: {name: 'rkdh', events: {click: this.handleAuditPass}}
          },
          {field: 'sbmc', title: '设备名称', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {
            field: 'ccbm',
            title: '出厂编码',
            minWidth: "160px",
            align: 'center',
            headerAlign: 'center',
            cellRender: {name: 'ccbm', events: {click: this.handleShow}}
          },
          {field: 'sblxmc', title: '设备类型', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'pt', title: 'PT', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'ct', title: 'CT', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'djrq', title: '入库日期', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'sskfmc', title: '库房名称', minWidth: "160px", align: 'center', headerAlign: 'center'},
          {field: 'sbgg', title: '规格', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'xh', title: '型号', minWidth: "160px", align: 'center', headerAlign: 'center',},
          {field: 'yxztmc', title: '运行状态', minWidth: "160px", align: 'center', headerAlign: 'center',},

        ],
        checkboxConfig: {
          // labelField: 'id',
          reserve: true,
          highlight: true,
          range: true
        },
        editConfig: {
          trigger: 'click',
          mode: 'row',
          showStatus: true
        }
      },
      //  api: 'fetchQueryQueryRwxqByPage',
      // init: true
      kfOptions: [],
      enableDefault: true
    }
  },
  created() {
    this.setReadModel()
  },
  mounted() {
    this.$nextTick(function () {
      this.fetchgldwOptions()
      this.fetchsblxOptions()
    })
    window.addEventListener('resize', this.setTableHeight);
  },
  destroyed: function () {
    window.removeEventListener('resize', this.setTableHeight);
  },
  methods: {
    timeformat(dat, value, type) {
      let year = dat.getFullYear();
      let mon = (dat.getMonth() + 1) < 10 ? "0" + (dat.getMonth() + 1) : dat.getMonth() + 1;
      let data = dat.getDate() < 10 ? "0" + (dat.getDate() - value) : dat.getDate() + value;
      if (type === 'start') {
        var newDate = year + "-" + mon + "-" + data + " 00:00:00";
      } else {
        var newDate = year + "-" + mon + "-" + data + " 23:59:59";
      }
      return newDate;
    },
    formResetEvent({data}) { // 重置表单
      let datatime = new Date()
      data['djrq'] = this.timeformat(datatime, 0, 'start')
      data['djrq_to'] = this.timeformat(datatime, 0, 'end')
      const item = this.$refs.xGrid.getFormItems(7)
      item.itemRender.options = []
    },
    // 高度自适应
    setTableHeight: function () {
      const tableContainer = document.querySelector("#app");
      const height = tableContainer.clientHeight;
      this.grid_options.height = height - 5;
    },
    //查询控制
    setReadModel() { //控制是否显示
      const isRead = util.isReadModel()
      if (isRead) {
        this.grid_options.toolbarConfig.buttons = []
      }
    },
    initFormData(form) {
      const that = this;
      let datatime = new Date()
      if (that.enableDefault) {
        // 查询框默认值初识化
        if (this.row !== undefined) {
          form.djrq = this.formData.jhkssj
          form.djrq_to = this.formData.endTime
        } else {
          form.djrq = this.timeformat(datatime, 0, 'start')
          form.djrq_to = this.timeformat(datatime, 0, 'end')
          console.log(form.djrq, form.djrq_to)
        }
        this.enableDefault = false;
      }
    },
    queryData: (page, formData) => {
      const queryParams = {
        pageSize: page.pageSize,
        pageNo: page.currentPage,
        entity: {
          gldwbm: formData.gldwbm ? formData.gldwbm : null,
          djbm: formData.djbm ? formData.djbm : null,
          ccbm: formData.ccbm ? formData.ccbm : null,
          sbmc: formData.sbmc ? formData.sbmc : null,
          sblxbm: formData.sblxbm ? formData.sblxbm : null,
          sskfbm: formData.sskfbm ? formData.sskfbm : null,
          djrq: formData.djrq ? formData.djrq + ' 00' + ":" + '00' + ":" + '00' : null,
          djrq_to: formData.djrq ? formData.djrq_to + ' 23' + ":" + '59' + ":" + '59' : null,
          type: '0'
        },
        paramsMap: {},
        column: '',
        order: ''
      }
      return godownEntryApi.getEquipDetailPage(queryParams)
    },
    addRowModal() {
      this.$refs.equipmentDdetail.showDialog()
    },
    fetchsblxOptions() {
      accountQueryApi.queryDictDatasb('1000').then(res => {
        let optionList = [
          {label: '请选择', value: ''}
        ]
        res.data.forEach((item) => {
          optionList.push({label: item.name, value: item.id})
        })
        const item = this.$refs.xGrid.getFormItems(6)
        item.itemRender.options = optionList
      }).catch(err => {
        console.log(err)
      })
    },
    fetchgldwOptions() {
      getInfo().then(res => {
        let params = {
          deptId: res.user.dept.deptId,
          parentId: res.user.dept.parentId
        }
        listDept(params).then(result => {
          let optionList = [
            {label: '请选择', value: ''}
          ]
          result.data.forEach((item) => {
            optionList.push({label: item.deptName, value: item.deptId})

          })
          const item = this.$refs.xGrid.getFormItems(0)
          item.itemRender.options = optionList

        })
      })
    },
    gldwbmChangeEvent(value) {
      this.$refs.xGrid._data.formData.sskfbm = null
      warehouseManagement.getKfByGldw(value.data.gldwbm).then(res => {
        // 修改编辑框
        // const sexColumn = $grid.getColumnByField('sex')
        // sexColumn.editRender.options = sexList
        // 修改查询条件列表
        let optionList = [
          {label: '请选择', value: ''}
        ]
        res.data.forEach((item) => {
          // console.log(item,'item.,,,');
          optionList.push({label: item.kfName, value: item.id})
        })
        const item = this.$refs.xGrid.getFormItems(7)
        item.itemRender.options = optionList
      })
    },
    handleAuditPass(val) {
      this.$refs.equipmentDdetail.showDialog(false, val, true)
      // this.$refs.godownEntry.showDialog(true, rowArr[0])
    },
    handleShow(val) {
      this.$refs.equipmentMaintenanceForm.showDialog(false, val, true)
    },
    closeEvent() {
      this.$refs.xGrid.commitProxy('query')
    },
    //导出
    exportModal() {
      // const dataParams={}
      const queryParam = Object.assign({}, this.$refs.xGrid.getProxyInfo().form)
      queryParam.type = '0'
      const queryParams = {
        entity: queryParam,
        column: "",
        order: "",
        pageSize: this.$refs.xGrid._data.tablePage.pageSize,
        pageNo: this.$refs.xGrid._data.tablePage.currentPage,
        paramsMap: {}
      }
      godownEntryApi.exportXls(queryParams).then(res => {
        util.download(res, '设备入库详情' + (moment().format("YYYY-MM-DD")) + '.xls')
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
// 创建一个简单的工具栏-左侧按钮渲染
// VXETable.renderer.add('add', {
//   renderToolbarButton(h, renderOpts, params) {
//     const {events = {}} = renderOpts
//     const {button, $table} = params
//     return [
//       <vxe-button icon="fa fa-plus (alias)" content="详细信息" onClick={
//         () => {
//           events.click(button)
//         }
//       }></vxe-button>
//     ]
//   }
// })
//入库编号穿透渲染
VXETable.renderer.add('rkdh', {
  renderDefault(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {row, column} = params
    return [
      <span style="color:#0000FF;cursor: pointer;" onClick={
        () => {
          events.click(params.row)
        }
      }>{params.row.djbm}</span>
    ]
  }
})
//出厂编码穿透渲染
VXETable.renderer.add('ccbm', {
  renderDefault(h, renderOpts, params) {
    const {events = {}} = renderOpts
    const {row, column} = params
    return [
      <span style="color:#0000FF;cursor: pointer;" onClick={
        () => {
          events.click(params.row)
        }
      }>{params.row.ccbm}</span>
    ]
  }
})
</script>

<style scoped>
.export {
  color: var(--font-color) !important;
  border-color: var(--font-color) !important;
  background-color: var(--button-background-color) !important;
  border-radius: 5% !important;
  margin-left: 0.2em !important;
  padding: 0 0.5em !important;
  min-width: 34px;
  width: 36px !important;
  height: 36px !important;
  float: right;
}
</style>
